#include "stm32f10x.h"
#include <stdio.h>
#include <string.h>
#include "packet.h"


uint16_t m_field_offset = 0;
uint8_t m_receive_state = RFID_PACKET_STATE_SOF;

//rfid_resp_packet_t rfid_pack_list[10]
rfid_resp_packet_t m_receive_packet;

uint16_t packet_len = 0;


int8_t memcpy_so(void *s1, int16_t offset, int16_t size, void *s2, int16_t n)
{
    if (offset >= size)
    {
        return -1;
    }

    if (offset + n > size)
    {
        n = size - offset;
    }

    memcpy(((int8_t*)s1)+offset, s2, n);

    return 0;
}

uint8_t packet_receiveNext(uint8_t *dat, uint16_t len, rfid_resp_packet_t *packet)
{
	int8_t ok = 0;
	uint8_t offset = 0;
	uint8_t copy_len = 0;

	while(!ok && (offset < len))
	{
		ok = 1;
		
		switch(m_receive_state)
		{
			case RFID_PACKET_STATE_SOF:
			{
				while(offset < len)
				{
					if(dat[offset] == RFID_PACKET_SOF)
					{
						m_receive_packet.sof = dat[offset];
						offset++;
						m_receive_state = RFID_PACKET_STATE_DATA;
						ok = (offset > len);
						m_field_offset = 0;
						break;
					}
					
					offset++;
				}
			}
			break;
			
			case RFID_PACKET_STATE_DATA:
			{
				if(m_field_offset == 0)
				{
					packet_len = dat[offset]; //length
					if(packet_len > 30)
					{
						m_receive_state = RFID_PACKET_STATE_SOF;
						break;
					}
				}

				copy_len = packet_len - m_field_offset;
				copy_len = ((len - offset) > copy_len) ? copy_len : (len - offset);
				if(copy_len > 0)
				{
					memcpy_so((uint8_t *)(&m_receive_packet.length),
											m_field_offset,
											packet_len,
											dat + offset,
											copy_len);

					m_field_offset += copy_len;
					offset += copy_len;
				}
				
				if (m_field_offset >= packet_len)
				{
					/* receive header over */
					m_receive_state =  RFID_PACKET_STATE_EOF;
					m_field_offset = 0;
					ok = (offset >= len);
				}
			}
			break;
			
			case RFID_PACKET_STATE_EOF:
			{
				if(offset < len)
				{
					m_receive_packet.eof = dat[offset];
					offset++;
					
					ok = (offset >= len);
					
					m_receive_state = RFID_PACKET_STATE_SOF;
					
					if(m_receive_packet.eof == RFID_PACKET_EOF)
					{
						memcpy(packet, &m_receive_packet, sizeof(m_receive_packet));
						return 1;
					}
					
				}
			}
			break;
		}
	}
	
	return 0;
}

uint16_t generate_packet(uint8_t *dat, uint8_t cmd, uint16_t len, rfid_cmd_packet_t *packet)
{
	packet->sof = RFID_PACKET_SOF;
	packet->cmd = cmd;
	packet->length = len + 2;
	memcpy(packet->payload, dat, len);
	packet->payload[len] = RFID_PACKET_EOF;
	return packet->length + 2;
}




